<template>
  <div class="app-container">
    <div class="block">
      <el-row>
        <el-col :span="24">
          <el-button @click="save" size="mini" type="primary">{{active==3?"提交":"下一步"}}</el-button>
          <el-button @click="prev" size="mini" v-show="active>0">上一步</el-button>
        </el-col>
      </el-row>
    </div>
    <br>
    <div class="block">
      <el-steps :active="active" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品相册"></el-step>
        <el-step title="商品详情"></el-step>
        <el-step title="上架信息"></el-step>
      </el-steps>
    </div>
    <el-form :model="form" label-width="150px" v-show="active==0">
      <el-row>
        <el-col :span="24">
          <el-form-item label="名称">
            <el-input minlength=1 v-model="form.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="产品简介">
            <el-input minlength=1 v-model="form.remark"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="类别">
            <Treeselect :options="categories" placeholder="请选择商品类别" :normalizer="normalizer" v-model="form.idCategory"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="是否新品">
            <el-radio-group v-model="form.isNew">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="是否热卖">
            <el-radio-group v-model="form.isHot">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form label-width="150px" v-show="active==1">
      <el-row>
        <el-col :span="24">
          <el-form-item label="商品缩略图">
            <imageUpload v-model="picUploadValue" :limit="1" @fileList="getPicImageUrl"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="商品相册">
            <imageUpload v-model="galleryUploadValue" :limit="5" @fileList="getGalleryImageUrl"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div :class="{fullscreen:fullscreen}" class="tinymce-container editor-container" v-show="active==2">
      <tinymce-editor ref="editor" v-model="form.detail"></tinymce-editor>
    </div>
    <el-form label-width="150px" v-show="active==3">
      <el-row>
        <el-col :span="24">
          <el-form-item label="商品规格">
            <el-radio class="radio" label="one" v-model="spec">单规格</el-radio>
            <el-radio class="radio" label="more" v-model="spec" v-show="attrKeyList.length>0">多规格</el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="spec == 'one'">
          <el-form-item label="库存">
            <el-input-number :max="100000" :min="0" v-model="form.stock"></el-input-number>
          </el-form-item>
          <el-form-item label="市场价(分)">
            <el-input-number :max="10000000" :min="0" v-model="form.marketingPrice"></el-input-number>
          </el-form-item>
          <el-form-item label="价格(分)">
            <el-input-number :max="10000000" :min="0" v-model="form.price"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :offset="3" :span="18" style="overflow: auto; text-align: center;" v-else>
          <el-button @click="openAddSkuForm" style="margin-bottom: 10px;" type="primary">添加规格</el-button>
          <el-table
            :data="skuList"
            :row-class-name="tableRowClassName"
            style="margin-bottom: 20px;">
            <el-table-column
              label="规格"
              prop="codeName">
            </el-table-column>
            <el-table-column
              label="市场价"
              prop="marketingPrice">
            </el-table-column>
            <el-table-column
              label="价格(分)"
              prop="price">
            </el-table-column>
            <el-table-column
              label="库存"
              prop="stock">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  @click="removeSku(scope.$index)"
                  size="small"
                  type="danger">删除
                </el-button>
              </template>
            </el-table-column>

          </el-table>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog :visible.sync="specDialogFormVisible" title="SKU配置">
      <el-form :model="skuForm">
        <el-form-item label="已选规格" label-width="100px" prop="specs">
          <el-tag
            :key="tag.id"
            @close="removeTag(tag)"
            closable
            v-for="tag in tags">
            {{tag.attrVal}}
          </el-tag>
        </el-form-item>
        <el-row>
          <el-col :span="8">
            <el-form-item label="属性名" label-width="100px">
              <el-select
                @change="changeAttrKey"
                allow-create
                default-first-option
                filterable
                placeholder="属性名"
                v-model="attrKeySel">
                <el-option
                  :key="item.id"
                  :label="item.attrName"
                  :value="item.id"
                  v-for="item in attrKeyList">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="属性值" label-width="100px">
              <el-select
                allow-create
                default-first-option
                filterable
                placeholder="属性值"
                v-model="attrValSel">
                <el-option
                  :key="item.id"
                  :label="item.attrVal"
                  :value="item.id"
                  v-for="item in attrValListSel">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :offset="2" :span="6">
            <el-button @click="addToTag" type="success">添加规格</el-button>
          </el-col>
        </el-row>

        <el-form-item label="市场价(分)" label-width="100px">
          <el-input-number :max="100000" :min="0" v-model="skuForm.marketingPrice"></el-input-number>
        </el-form-item>
        <el-form-item label="价格(分)" label-width="100px">
          <el-input-number :max="1000000" :min="0" v-model="skuForm.price"></el-input-number>
        </el-form-item>
        <el-form-item label="库存" label-width="100px">
          <el-input-number :max="100000" :min="0" v-model="skuForm.stock"></el-input-number>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="closeAddSkuForm" type="default">取 消</el-button>
        <el-button @click="addSku" type="primary">确 定</el-button>
      </div>
    </el-dialog>
    <br>
    <div class="block">
      <el-row>
        <el-col :span="24">
          <el-button @click="save" size="mini" type="primary">{{active==3?"提交":"下一步"}}</el-button>
          <el-button @click="prev" size="mini" v-show="active>0">上一步</el-button>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
  import TinymceEditor from '@/components/tinymce-editor'
  import {getShopGoods, addShopGoods, updateShopGoods} from "@/api/shop/shopGoods";
  import {listShopCategory} from "@/api/shop/shopCategory";
  import {getAttrBy} from "@/api/shop/shopAttrVal";
  import {listShopGoodsSku, delShopGoodsSku, addShopGoodsSku } from "@/api/shop/shopGoodsSku";

  export default {
    name: 'edit',
    components: { TinymceEditor },
    data() {
      return {
        spec: 'one',
        specs: [],
        specDialogFormVisible: false,
        skuForm: {},
        attrKeySel: '',
        attrKeyList: [],
        attrValList: [],
        showAddAttrKey: false,
        attrKeyForm: {attrName: ''},
        attrValForm: {attrVal: ''},
        attrValSel: '',
        attrValListSel: [],
        tags: [],
        form: {
          id: undefined,
          name: undefined,
          price: undefined,
          stock: undefined,
          picOssId: undefined,
          picOssUrl: undefined,
          gallery: undefined,
          idCategory: undefined,
          isHot: undefined,
          isNew: undefined,
          detail: undefined,
          isDelete: undefined,
          isOnSale: undefined,
          likeNum: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          remark: undefined
        },
        skuList: [],
        idGoods: '',
        active: 0,
        categories: [],
        fullscreen: false,
        galleryList: [],
        picUploadValue: [],
        galleryUploadValue: []
      }
    },
    mounted() {
      this.init()
    },
    methods: {
      init() {
        this.idGoods = this.$route.query.id
        this.fetchData()
      },
      fetchData() {
        if (this.idGoods) {
          getShopGoods(this.idGoods).then(response => {
            this.form = response.data
            this.idGoods = this.form.id
            if (this.form.picOssId) {
              this.picUploadValue = [{ossId: this.form.picOssId, url: this.form.picOssUrl}];
            }
            this.skuList = response.data.skuVos;
            this.spec = this.skuList.length > 0 ? 'more' : 'one'
            let galleryArr = this.form.gallery.length > 0 ? JSON.parse(this.form.gallery) : [];
            for (let i = 0; i < galleryArr.length; i++) {
              if (galleryArr[i] != '') {
                this.galleryUploadValue.push({
                  ossId: galleryArr[i].ossId,
                  url: galleryArr[i].url
                })
              }
            }
            getAttrBy(this.form.idCategory).then(response2 => {
              this.attrKeyList = response2.data.keyList
              this.attrValList = response2.data.valList
            })
          })
        }
        listShopCategory().then(response => {
          this.categories = response.data
        })
      },
      prev() {
        if (this.active > 0) {
          this.active -= 1
        }
      },
      save() {
        if (!this.idGoods && this.active == 0) {
          //第一步提交的时候先保存下商品以便获取商品id
          if (this.form.name === '' ||
            this.form.idCategory === '' ||
            this.form.remark === '') {
            this.$message({
              message: '请输入必要的商品项目',
              type: 'error'
            })
            return
          }
          addShopGoods({
            name: this.form.name,
            idCategory: this.form.idCategory,
            remark: this.form.remark,
            isNew: this.form.isNew,
            isHot: this.form.isHot
          }).then(response => {
            this.idGoods = response.data
          })
          getAttrBy(this.form.idCategory).then(response2 => {
            this.attrKeyList = response2.data.keyList
            this.attrValList = response2.data.valList
          })
        }
        if (this.active < 3) {
          this.active++
          return
        }
        if (this.spec === 'more') {
          //如果商品配置多规格，则删除单规格配置
          this.form.price = ''
          this.form.marketingPrice = ''
          this.form.stock = ''
        }
        updateShopGoods({
          name: this.form.name,
          picOssId: this.form.picOssId,
          picOssUrl: this.form.picOssUrl,
          gallery: this.form.gallery,
          idCategory: this.form.idCategory,
          remark: this.form.remark,
          detail: this.form.detail,
          stock: this.form.stock,
          price: this.form.price,
          isDelete: this.form.isDelete,
          isOnSale: this.form.isOnSale,
          id: this.idGoods,
          isNew: this.form.isNew,
          isHot: this.form.isHot
        }).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.$router.push({path: 'shopGoods'});
        })
      },
      tableRowClassName(row, index) {
        if (index === 1) {
          return 'info-row'
        } else if (index === 3) {
          return 'positive-row'
        }
        return ''
      },
      changeAttrKey(val) {
        let attrValSel = []
        console.info(this.attrValList);
        for (let i = 0; i < this.attrValList.length; i++) {
          if (this.attrValList[i].idAttrKey === val) {
            attrValSel.push(this.attrValList[i])
          }
        }

        this.attrValListSel = attrValSel
        this.attrValSel = attrValSel[0].id
      },
      addToTag() {
        for (let i = 0; i < this.attrValList.length; i++) {
          if (this.attrValList[i].id === this.attrValSel) {
            const currentAttrVal = this.attrValList[i]
            let isRepeat = false
            let isRepeatAttrKey = false
            this.tags.forEach(function (val) {
              if (val.id === currentAttrVal.id) {
                isRepeat = true
              }
              if (val.idAttrKey === currentAttrVal.idAttrKey) {
                isRepeatAttrKey = true
              }
            })
            if (isRepeat === false && isRepeatAttrKey === false) {
              this.tags.push(currentAttrVal)
            } else {
              this.$message({
                message: isRepeat == true ? '请勿选择重复规格' : '该属性已经选择一种规格值',
                type: 'error'
              })
            }
            break
          }
        }
      },
      removeTag(tag) {
        this.tags.splice(this.tags.indexOf(tag), 1);
      },
      openAddSkuForm() {
        this.tags = []
        this.specDialogFormVisible = true
      },
      closeAddSkuForm() {
        this.specDialogFormVisible = false
      },
      getSkuCode() {
        let code = ''
        let codeName = ''
        for (let i = 0; i < this.tags.length; i++) {
          if (i === 0) {
            code = this.tags[i].id
            codeName = this.tags[i].attrVal
          } else {
            code += ',' + this.tags[i].id
            codeName += ',' + this.tags[i].attrVal
          }
        }
        return {code: code, codeName: codeName}
      },
      addSku() {
        if (this.tags.length == 0) {
          this.$message({
            message: '请选择商品规格',
            type: 'error'
          })
          return
        }
        if (!this.skuForm.stock) {
          this.$message({
            message: '请输入库存数量',
            type: 'error'
          })
          return
        }
        if (!this.skuForm.marketingPrice) {
          this.$message({
            message: '请输入市场价',
            type: 'error'
          })
          return
        }
        if (!this.skuForm.price) {
          this.$message({
            message: '请输入价格',
            type: 'error'
          })
          return
        }
        const skuCodeAndName = this.getSkuCode()
        addShopGoodsSku({
          idGoods: this.idGoods,
          marketingPrice: this.skuForm.marketingPrice,
          code: skuCodeAndName.code,
          codeName: skuCodeAndName.codeName,
          price: this.skuForm.price,
          stock: this.skuForm.stock
        }).then(response => {
          listShopGoodsSku({
            idGoods: this.idGoods,
            isDeleted: false
          }).then(response => {
            this.skuList = response.data;
            this.specDialogFormVisible = false
          });
        })
      },
      removeSku(index) {
        console.log(index)
        let records = this.skuList.splice(index, 1)
        const record = records[0]
        this.$modal.confirm('是否确认删除商品SKU编号为"' + record.id + '"的数据项？').then(() => {
          return delShopGoodsSku(record.id);
        }).then(() => {
          this.$modal.msgSuccess("删除成功");
          listShopGoodsSku({
            idGoods: this.idGoods,
            isDeleted: false
          }).then(response => {
            this.skuList = response.data;
          });
        }).catch(() => {
        }).finally(() => {
        });
      },
      getPicImageUrl(fileList) {
        if (fileList.length == 1) {
          this.form.picOssId = fileList[0].ossId;
          this.form.picOssUrl = fileList[0].url;
        } else {
          this.form.picOssId = "";
          this.form.picOssUrl = "";
        }
      },
      getGalleryImageUrl(fileList) {
        if (fileList.length >= 1) {
          this.form.gallery = JSON.stringify(fileList);
        }
      },
      normalizer(node) {
        //去掉children=null的属性
        if (node.children == null || node.children == 'null') {
          delete node.children;
        }
      },
    }
  }
</script>

<style scoped>

</style>
